import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import axios from 'axios'

interface MenuPermission {
  menu_path: string
  can_read: boolean
  can_write: boolean
}

interface UserInfo {
  id: number
  username: string
  is_superuser: boolean
  is_staff: boolean
}

export const usePermissionStore = defineStore('permission', () => {
  // 状态
  const permissions = ref<MenuPermission[]>([])
  const userInfo = ref<UserInfo | null>(null)
  const permissionsLoaded = ref(false)
  const loading = ref(false)

  // 计算属性
  const isSuperUser = computed(() => userInfo.value?.is_superuser || false)
  const isStaff = computed(() => userInfo.value?.is_staff || false)

  // 获取用户信息
  const loadUserInfo = async () => {
    try {
      const response = await axios.get('/api/auth/user/')
      userInfo.value = response.data
      console.log('用户信息加载成功:', userInfo.value)
    } catch (error) {
      console.error('获取用户信息失败:', error)
      userInfo.value = null
    }
  }

  // 加载用户权限
  const loadPermissions = async () => {
    if (loading.value) return
    
    loading.value = true
    try {
      // 先加载用户信息
      await loadUserInfo()

      // 如果是超级管理员，不需要加载具体权限
      if (isSuperUser.value) {
        permissions.value = []
        permissionsLoaded.value = true
        console.log('超级管理员，跳过权限加载')
        return
      }

      // 加载用户菜单权限
      const response = await axios.get('/api/user-permissions/')
      permissions.value = response.data || []
      permissionsLoaded.value = true
      
      console.log('用户权限加载成功:', permissions.value)
    } catch (error) {
      console.error('加载权限失败:', error)
      permissions.value = []
      permissionsLoaded.value = true
    } finally {
      loading.value = false
    }
  }

  // 刷新权限
  const refreshPermissions = async () => {
    permissionsLoaded.value = false
    await loadPermissions()
  }

  // 检查读权限
  const canRead = (menuPath: string): boolean => {
    // 超级管理员拥有所有权限
    if (isSuperUser.value) return true
    
    // 如果权限未加载完成，默认允许（避免闪烁）
    if (!permissionsLoaded.value) return true

    // 查找对应菜单的权限
    const permission = permissions.value.find(p => p.menu_path === menuPath)
    return permission?.can_read || false
  }

  // 检查写权限
  const canWrite = (menuPath: string): boolean => {
    // 超级管理员拥有所有权限
    if (isSuperUser.value) return true
    
    // 如果权限未加载完成，默认允许（避免闪烁）
    if (!permissionsLoaded.value) return true

    // 查找对应菜单的权限
    const permission = permissions.value.find(p => p.menu_path === menuPath)
    return permission?.can_write || false
  }

  // 检查特定操作权限
  const canPerformAction = (menuPath: string, action: 'read' | 'write' | 'create' | 'update' | 'delete'): boolean => {
    switch (action) {
      case 'read':
        return canRead(menuPath)
      case 'write':
      case 'create':
      case 'update':
      case 'delete':
        return canWrite(menuPath)
      default:
        return false
    }
  }

  // 获取菜单权限详情
  const getMenuPermission = (menuPath: string): MenuPermission | null => {
    return permissions.value.find(p => p.menu_path === menuPath) || null
  }

  // 获取所有权限
  const getAllPermissions = () => {
    return permissions.value
  }

  // 清除权限（用于登出）
  const clearPermissions = () => {
    permissions.value = []
    userInfo.value = null
    permissionsLoaded.value = false
  }

  return {
    // 状态
    permissions,
    userInfo,
    permissionsLoaded,
    loading,
    
    // 计算属性
    isSuperUser,
    isStaff,
    
    // 方法
    loadPermissions,
    refreshPermissions,
    canRead,
    canWrite,
    canPerformAction,
    getMenuPermission,
    getAllPermissions,
    clearPermissions
  }
})
